package com.schoolvisitors.controller;

import com.schoolvisitors.response.ResultBody;
import com.schoolvisitors.response.ResultCode;
import jakarta.servlet.RequestDispatcher;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

@RestController
@RequestMapping("${server.error.path:/error}")
public class GlobalErrorController implements ErrorController {

    @RequestMapping
    public ResponseEntity<Map<String, Object>> handleError(HttpServletRequest request) {
        Object statusObj = request.getAttribute(RequestDispatcher.ERROR_STATUS_CODE);
        int statusCode = statusObj != null ? Integer.parseInt(statusObj.toString()) : 500;

        String uri = (String) request.getAttribute(RequestDispatcher.ERROR_REQUEST_URI);
        if (statusCode == 400) {
            return ResponseEntity.status(400).body(ResultBody.body(false, 405,"请求参数错误"));
        } else if (statusCode == 404) {
            return  ResponseEntity.status(404).body(ResultBody.body(false, 404,"找不到资源")); //ResultBody.error(ResultCode.CODE_404);
        } else if (statusCode == 405) {
            return ResponseEntity.status(405).body(ResultBody.body(false, 405,"请求方法不支持"));
        } else {
            return ResponseEntity.status(500).body(ResultBody.body(false, 500,"服务器错误"));
        }
    }
}